﻿using LogicCenter.Threads;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tools.Base;

namespace LogicCenter
{
    partial class Program
    {
        static void Main(string[] args)
        {
            Console.BufferHeight = 500;
            Console.WindowHeight = 40;
            //Conso

            ThreadManager.Init();

            RunProgram_Input(args);

            // 留点时间，查看一下尾部信息
            //Thread.Sleep(1000);
        }

        public static void RunProgram_Input(string[] args)
        {
            InitCommonCmd();

            Thread thread = new Thread(ThreadFunc_ConsoleInput)
            {
                IsBackground = true
            };

            thread.Start();
            while (!NeedExitServer || !CanExitServer)
            {
                Thread.Sleep(1000);
            }
            thread.Abort();
        }

        /// <summary>
        /// 控制台指令的线程函数
        /// </summary>
        public static void ThreadFunc_ConsoleInput()
        {
            Console.Title = "LogicCenter";

            while (!NeedExitServer)
            {
                string cmd = Console.ReadLine();
                if (!string.IsNullOrEmpty(cmd))
                {
                    if (0 == cmd.CompareTo("exit"))
                    {
                        MyConsole.WriteLineEx("确认退出吗(输入 y 将立即退出)？");
                        cmd = Console.ReadLine();
                        if (0 == cmd.CompareTo("y"))
                        {
                            break;
                        }
                    }
                    else
                    {
                        ParseInputCmd(cmd);
                    }
                }
            }

            

            ExitServer();
        }

        private static int _NeedExitServer = 0;
        private static int _CanExitServer = 0;
        public static bool NeedExitServer{get{ return _NeedExitServer == 1;} }
        public static bool CanExitServer { get { return _CanExitServer == 1; } }

        private static void ExitServer()
        {
            int nOriginalValue = Interlocked.Exchange(ref _NeedExitServer, 1);
            if (nOriginalValue == 1)
                return;

            // 线程起搏器停止
            ThreadManager.StopBackThreadDriver();

            // 等待其他线程退出
            ThreadManager.WaitForExit();

            Interlocked.Exchange(ref _CanExitServer, 1);
        }
    }
}
